const luluService = require('./luluService.js')

class LuluController {
  async getKeys(req, res, next) {
    try {
      const data = await luluService.getKeys(req.query)
      res.status(200).json({
        code: 200,
        success: true,
        data,
      })
    } catch (error) {
      next(error)
    }
  }

  async login(req, res, next) {
    try {
      const data = await luluService.login(req.body)
      res.status(200).json({
        code: 200,
        success: true,
        data,
      })
    } catch (error) {
      next(error)
    }
  }

  async getMenus(req, res, next) {
    try {
      const data = await luluService.getMenus(req.query)
      res.status(200).json({
        code: 200,
        success: true,
        data,
      })
    } catch (error) {
      next(error)
    }
  }

  // 账号管理相关接口
  // 获取用户列表
  async getUserList(req, res, next) {
    try {
      // await new Promise(resolve => setTimeout(resolve, 2000));
      const data = await luluService.getUserList(req.query)
      res.status(200).json({
        code: 200,
        success: true,
        data,
        message: '获取用户列表成功'
      })
    } catch (error) {
      next(error)
    }
  }

  // 创建用户
  async createUser(req, res, next) {
    try {
      const data = await luluService.createUser(req.body)
      res.status(201).json({
        code: 201,
        success: true,
        data,
        message: '用户创建成功'
      })
    } catch (error) {
      next(error)
    }
  }

  // 更新用户
  async updateUser(req, res, next) {
    try {
      const { id } = req.params
      const data = await luluService.updateUser(id, req.body)
      res.status(200).json({
        code: 200,
        success: true,
        data,
        message: '用户更新成功'
      })
    } catch (error) {
      next(error)
    }
  }

  // 删除用户
  async deleteUser(req, res, next) {
    try {
      const { id } = req.params
      const data = await luluService.deleteUser(id)
      res.status(200).json({
        code: 200,
        success: true,
        data,
        message: '用户删除成功'
      })
    } catch (error) {
      next(error)
    }
  }

  // 更新用户状态
  async updateUserStatus(req, res, next) {
    try {
      const { id } = req.params
      const { status } = req.body
      const data = await luluService.updateUserStatus(id, status)
      res.status(200).json({
        code: 200,
        success: true,
        data,
        message: data.message
      })
    } catch (error) {
      next(error)
    }
  }

  // 重置密码
  async resetPassword(req, res, next) {
    try {
      const { id } = req.params
      const data = await luluService.resetPassword(id)
      res.status(200).json({
        code: 200,
        success: true,
        data,
        message: data.message
      })
    } catch (error) {
      next(error)
    }
  }

  // 获取用户详情
  async getUserById(req, res, next) {
    try {
      const { id } = req.params
      const data = await luluService.getUserById(id)
      res.status(200).json({
        code: 200,
        success: true,
        data,
        message: '获取用户详情成功'
      })
    } catch (error) {
      next(error)
    }
  }

  // 获取组织列表
  async getOrganizations(req, res, next) {
    try {
      const data = await luluService.getOrganizations()
      res.status(200).json({
        code: 200,
        success: true,
        data,
        message: '获取组织列表成功'
      })
    } catch (error) {
      next(error)
    }
  }

  // 获取角色列表
  async getRoles(req, res, next) {
    try {
      const data = await luluService.getRoles()
      res.status(200).json({
        code: 200,
        success: true,
        data,
        message: '获取角色列表成功'
      })
    } catch (error) {
      next(error)
    }
  }

  // 获取组织树
  async getOrgTree(req, res, next) {
    try {
      const data = await luluService.getOrgTree()
      res.status(200).json({
        code: 200,
        success: true,
        data,
        message: '获取组织树成功'
      })
    } catch (error) {
      next(error)
    }
  }

  // 重定向到 React 官网 - 返回重定向URL（推荐方式）
  async redirectToReact(req, res, next) {
    try {
      const data = await luluService.redirectToReact()
      res.status(200).json({
        code: 200,
        success: true,
        data,
        message: data.message
      })
    } catch (error) {
      next(error)
    }
  }

  // 直接重定向到 React 官网（302重定向）
  async directRedirectToReact(req, res, next) {
    try {
      res.redirect(302, 'https://react.dev/')
    } catch (error) {
      next(error)
    }
  }

  // 生成图片验证码
  async generateImageCode(req, res, next) {
    try {
      const data = await luluService.generateImageCode()
      
      // 将验证码存储到session中
      req.session.captcha = {
        code: data.code,
        timestamp: Date.now()
      }
      
      // 设置响应头为图片类型
      res.set({
        'Content-Type': 'image/svg+xml',
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires': '0'
      })
      
      // 返回图片数据
      res.status(200).send(data.image)
      
      // 开发阶段在控制台输出验证码
      console.log('生成的验证码:', data.code, '- 存储到session ID:', req.sessionID)
    } catch (error) {
      next(error)
    }
  }

  // 验证图片验证码
  async verifyCaptcha(req, res, next) {
    try {
      const { code } = req.body
      
      if (!code) {
        return res.status(400).json({
          code: 400,
          success: false,
          message: '请输入验证码'
        })
      }

      if (!req.session.captcha) {
        return res.status(400).json({
          code: 400,
          success: false,
          message: '验证码已过期，请重新获取'
        })
      }

      const { code: sessionCode, timestamp } = req.session.captcha
      const now = Date.now()
      const codeExpireTime = 5 * 60 * 1000 // 5分钟过期

      // 检查验证码是否过期
      if (now - timestamp > codeExpireTime) {
        delete req.session.captcha
        return res.status(400).json({
          code: 400,
          success: false,
          message: '验证码已过期，请重新获取'
        })
      }

      // 验证码比较（不区分大小写）
      if (code.toLowerCase() !== sessionCode.toLowerCase()) {
        return res.status(400).json({
          code: 400,
          success: false,
          message: '验证码错误'
        })
      }

      // 验证成功后删除session中的验证码（一次性使用）
      delete req.session.captcha

      res.status(200).json({
        code: 200,
        success: true,
        message: '验证码验证成功'
      })
    } catch (error) {
      next(error)
    }
  }
}

module.exports = new LuluController()
